package wh.ispct.util

import java.awt.event.ItemEvent;

import wh.ispct.Menu

/**
 * 显示树数据的Groovy类
 * 
 * @author zhou
 *
 */
/**
 * 作为树缓存数据
 * @author zhou
 *
 * @param <T>
 */
class ExtTreeData<T> {
	public List<ExtTreeNode> roots = new ArrayList<ExtTreeNode>()

	List<ExtTreeNode> getRoots(){
		return roots
	}

	/**
	 * 递归读取树
	 * @param visitClosure
	 * @return
	 */
	def visit(Closure visitClosure){
		visitTreeNodes(this.roots,visitClosure)
	}

	def visitTreeNodes(List<ExtTreeNode> nodes,Closure visitClosure){
		nodes.each {it ->
			visitClosure(it)
			if(it.children != null){
				visitTreeNodes(it.children,visitClosure)
			}
		}
	}

	/**
	 * 添加Node 到nodes
	 * @param list 实体类列表
	 * @param nodeConvertor 节点转换器
	 */
	public void addNodes(List<T> list, Closure nodeMapper){
		List<ExtTreeNode> nodes = new ArrayList<ExtTreeNode>()
		for(T t : list)
			nodes.add( nodeMapper(t))

		roots = nodes.findAll  {
			(it.parentId == null) ? [it]: []
		}

		roots.sort {a, b -> return a.sort - b.sort }

		//遍历跟节点，找到对应的子节点
		roots.each ({ root ->
			appendChildren(root,nodes)
		})

	}

	/**
	 * 递归增加子节点
	 * 
	 * @param node
	 * @param nodes
	 */
	void appendChildren(node,nodes){
		List<ExtTreeNode> children = nodes.findAll({ it.parentId == node.id})
		node.setChildren(children)
		children.each ({ it ->
			appendChildren(it,nodes)
		})
	}
}
